﻿using System;
using System.Collections.Generic;
using System.Linq;
using Torrenter.Common.Objects;
using System.Net;
using System.IO;

namespace Torrenter.Manager.Services
{
    public class TorrentManager
    {
        #region static members

        public static TorrentManager Instance = new TorrentManager();

        static TorrentManager()
        {
        }

        #endregion // static members


        #region public properties

        public const string DownloadDirName = "Torrents";

        public string TorrentDownloadDirName { get; set; }

        public string DownloadLocation
        {
            get
            {
                return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TorrentDownloadDirName);
            }
        }

        public TorrentRepository Torrents {get; set;}


        #endregion // public properties

        public void SaveTorrents()
        {
            Torrents.SaveTorrents();
        }

        /// <summary>
        /// try to take all the current trackers and check if they missing files can be download
        /// </summary>
        public void TryUpdateNewTorrents()
        {
            foreach (var show in Torrents.Shows)
            {
                GetTorrent(show);
            }
            SaveTorrents();
        }

        #region add methods

        public ShowSeason AddTorrent(ShowSeason showSeason)
        {
            Torrents.AddSeason(showSeason);
            var season = GetTorrent(showSeason);            
            SaveTorrents();
            return season;
        }

        #endregion // add methods

        #region get methods

        private Torrent GetTorrentFromSearch(SingleEpTorrentSearch search)
        {
            SearcherService s = new SearcherService();
            var torrent = s.SearchTorrent(search);
            if (torrent == null)
            {
                return null;
            }
            try
            {
                System.Diagnostics.Process.Start(torrent.DownloadLocation);
            }
            catch{}
            #region old code

            //catch (Exception)
            //{

            //    throw;
            //}

            //Download(torrent);

            ////AddTorrentToUTorrent
            //try
            //{ //try to add the torrent
            //    System.Diagnostics.Process.Start(torrent.LocalPath);
            //}
            //catch (Exception)
            //{

            //    //TODO: what do you do here???
            //}


            #endregion // old code
            
            return torrent;
        }

        public Torrent GetTorrent(Torrent torrent)
        {
            var search = new SingleEpTorrentSearch(torrent);
            return GetTorrentFromSearch(search);
        }

        /// <summary>
        /// get the torrents from the show until it doesn't find the next torrent
        /// </summary>
        /// <param name="show"></param>
        public void GetTorrent(Show show)
        {
            var torrent = show.GetNextEpisode();
            while (torrent != null)
            {
                GetTorrent(torrent);
                torrent = show.GetNextEpisode();
            }
        }

        public ShowSeason GetTorrent(ShowSeason season)
        {
            foreach (var ep in season.Episondes)
            {
                if (GetTorrent(ep) == null)
                {break; }

            }
            //season.Episondes = torrents;
            return season;
        }

        #endregion // get methods
        

        public TorrentManager()
        {
            TorrentDownloadDirName = DownloadDirName;
            Torrents = TorrentRepository.GetTorrents();
        }


        #region Download methods

        /// <summary>
        /// download the torrent to the torrents lib
        /// </summary>
        /// <param name="uri">the torrent location</param>
        /// <returns>true for success</returns>
        private void Download(string uri, string localDir)
        {
            WebClient wc = new WebClient();
            wc.DownloadFile(uri, localDir);
        }

        public void Download(Torrent torrent)
        {
            var uri = torrent.DownloadLocation;
            if (!Directory.Exists(DownloadLocation))
            {
                Directory.CreateDirectory(DownloadLocation);
            }
            var location = Path.Combine(DownloadLocation, uri.Split('/').Last());

            Download(uri, location);
            torrent.LocalPath = location;
        }


        #endregion // Download methods

        
    }
}
